﻿using System;
using System.Collections.Generic;
using System.Linq;
using Actya.Core.Security;
using Actya.Core.SiteStructure;
using Actya.Core.Widgets;

namespace Actya.Core.Infrastructure
{
	public class CmsContext : ICmsContext
	{
		private readonly IWidgetService _widgetService;
		private DateTime _contextStarted;

		public ICmsHost Host { get; private set; }
		public Site Site { get; set; }
		public Page Page { get; set; }
		public User User { get; set; }

		public CmsContext (ICmsHost cmsHost, IWidgetService widgetService)
		{
			_widgetService = widgetService;
			this.Host = cmsHost;
			this._contextStarted = DateTime.Now;
		}

		public SitemapNode GetCurrentSitemapNode()
		{
			if (this.Page != null && this.Site != null)
			{
				return this.Site.AllSitemapNodes.SingleOrDefault(n => n.IsPrimaryPageReference && n.PageId == this.Page.Id);
			}
			return null;
		}

		public PageLayout GetCurrentPageLayout()
		{
			if (this.Page != null && this.Site != null)
			{
				return this.Site.GetPageLayoutById(this.Page.Layout);
			}
			return null;
		}

		public Theme GetCurrentTheme()
		{
			if (this.Site != null)
			{
				var currentLayout = GetCurrentPageLayout();
				if (currentLayout != null && ! String.IsNullOrEmpty(currentLayout.Theme))
				{
					return this.Site.GetThemeByName(currentLayout.Theme);
				}
				return this.Site.GetThemeByName(this.Site.DefaultTheme);
			}
			return null;
		}

		public IDictionary<string, IEnumerable<IWidget>> GetCurrentWidgets()
		{
			var currentWidgets = new Dictionary<string, IEnumerable<IWidget>>();
			var currentLayout = GetCurrentPageLayout();
			if (currentLayout != null)
			{
				var widgets = GetWidgetsForPageLayout(currentLayout);
				foreach (var widgetItem in currentLayout.Widgets)
				{
					currentWidgets.Add(widgetItem.Key, widgets.Where(w => widgetItem.Value.Contains(w.Id)));
				}
			}
			return currentWidgets;
		}

		public IEnumerable<IWidget> GetWidgetsForPageLayout(PageLayout pageLayout)
		{
			var widgetIdsFromLayout = pageLayout.Widgets.SelectMany(w => w.Value);
			return GetWidgets(widgetIdsFromLayout.ToArray());
		}

		public IEnumerable<IWidget> GetWidgets(string[] widgetIds)
		{
			return _widgetService.GetWidgetsByIds(widgetIds);
		}
	}
}